package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.*;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Service
//@Transactional  暂时先别管事务
public class DestinationServiceImpl implements IDestinationService {

    @Autowired
    private DestinationRepository destinationRepository;
    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyThemeService strategyThemeService;
    @Autowired
    private IStrategyCatalogService strategyCatalogService;
    @Autowired
    private IDestinationService destinationService;



    @Override
    public List<Destination> selectAll() {
        //调用目的地的repository
        List<Destination> all = destinationRepository.findAll();
        return all;
    }

    @Override
    public List<Destination> selectDestsByReginoId(String rid) {
        //根据id查出区域对象
        Region region = regionRepository.findById(rid).orElse(null);
        if (region==null){
            return new ArrayList<>();
        }
        //拿到对象里的目的地id们
        List<String> refIds = region.getRefIds();
        //根据这些id查询出对象,返回
        List<Destination> byIdIn = destinationRepository.findByIdIn(refIds);


        return byIdIn;
    }

    @Override
    public Page<Destination> query(DestinationQuery qo) {
        //创建Query对象,根据过滤条件查询总条数,此处没有限制条件,所以用空的查询对象查
        Query query = new Query();
        //创建过滤查询
        if (StringUtils.hasLength(qo.getParentId())){
            Criteria criteria=Criteria.where("parentId").is(qo.getParentId());
            query.addCriteria(criteria);
        }
        if (StringUtils.hasLength(qo.getKeyword())){
            Criteria criteria=Criteria.where("name").regex(qo.getKeyword());
            query.addCriteria(criteria);
        }
        //有数据,进行分页操作,创建新的分页对象,此索引从0开始,所以要减一,分页的字段与数据库一致
        Pageable pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        //返回给控制器
        return DBHelper.query(template, Destination.class, query, pageAble);
    }

    @Override
    public void update(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void updateInfo(String id,String info) {
        //先查询
        Destination destination = destinationRepository.findById(id).get();
        //再修改
        destination.setInfo(info);
        //最后更新
        destinationRepository.save(destination);
    }

    @Override
    public void save(Destination destination) {
        destination.setId(null);
        destinationRepository.save(destination);
    }

    @Override
    public void deleteById(String id) {
        destinationRepository.deleteById(id);
    }

    @Override
    public List<Destination> getToasts(DestinationQuery qo) {
        //查父目的地,如果有父id
        List<Destination> list=new ArrayList<>();
        if (!StringUtils.hasLength(qo.getParentId())){
            return list;
        }
        Destination destination = destinationRepository.findById(qo.getParentId()).get();
        list.add(destination);
        //while循环,查父区域的父区域
        while (StringUtils.hasLength(destination.getParentId())){
            destination=destinationRepository.findById(destination.getParentId()).get();
            list.add(destination);
        }
        Collections.reverse(list);
        return list;
    }

    @Override
    public List<Region> selectHotRegion() {
        return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }

    @Override
    public void addDest(Strategy strategy) {
        /**
         * 给strategy添加三个属性  1目的地id  2.目的地名字   3.是否为国外
         * @param strategy
         */
        //根据分类id查询出分类对象
        StrategyCatalog sc = strategyCatalogService.get(strategy.getCatalogId());
        //给攻略对象添加属性
        strategy.setDestId(sc.getDestId());
        strategy.setDestName(sc.getDestName());
        //判断是否为国外,吐司,以目的地为条件查最上层建筑
        DestinationQuery qo = new DestinationQuery();
        qo.setParentId(sc.getDestId());
        List<Destination> toasts = this.getToasts(qo);
        if (!"中国".equals(toasts.get(0).getName())){
            strategy.setIsabroad(1);
        }
    }

    @Override
    public List<Destination> getToasts(String destId) {
        DestinationQuery destinationQuery = new DestinationQuery();
        destinationQuery.setParentId(destId);
        List<Destination> toasts = getToasts(destinationQuery);
        return toasts;
    }

    @Override
    public Destination get(String destId) {
        return destinationRepository.findById(destId).get();
    }

    @Override
    public Destination getByName(String keyword) {
        List<Destination> list = destinationRepository.findByName(keyword);
        if (list!=null&&list.size()>0){
            return list.get(0);
        }else {
            return null;
        }

    }

    @Override
    public List<Destination> selectDestsByReginoIdQ(String regionId) {
        //根据regionId查询region对象
        //如果regionId为-1,则查国内,直接根据名字查
        List<Destination> list;
        if (regionId.equals("-1")){
            list = destinationRepository.findByParentName("中国");
        }else {
            Region region = regionRepository.findById(regionId).get();
            //得到region对象底下的关联集合
            List<String> refIds = region.getRefIds();
            //根据关联集合id们查询所有目的地对象并返回
            list = destinationRepository.findByIdIn(refIds);
        }
        //遍历list的每一项,给下加第二级数据
        for (Destination destination : list) {
            //得到当前高层目的地的id
            String id = destination.getId();
            //根据高层id查子数据,只要5个
            Pageable pageable= PageRequest.of(0, 5, Sort.Direction.ASC,"_id");
            List<Destination> byParentId = destinationRepository.findByParentId(id, pageable);
            destination.setChildren(byParentId);
        }
        return list;
    }
}
